package models

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/go-redis/redis/v8"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/setting"
)

// PutSession save into redis
func PutSession(userID uint64, userRole string) error {
	idString := fmt.Sprintf("%d", userID)
	ctx := context.Background()
	err := redisDB.SetEX(ctx, "user_"+idString, userRole, time.Duration(setting.JwtLifetime)*time.Minute).Err()
	if err != nil {
		log.Println(err)
	}
	return err
}

// ExistsSession exam is the session exists in redis
func ExistsSession(userID uint64) (bool, string) {
	idString := fmt.Sprintf("%d", userID)
	ctx := context.Background()
	role, err := redisDB.Get(ctx, "user_"+idString).Result()
	if err == redis.Nil {
		return false, ""
	} else if err != nil {
		log.Println(err)
		return false, ""
	}
	return true, role
}
